package org.zachary.creditbusiness.hotel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zachary.creditbusiness.hotel.entity.Hotel;
import org.zachary.creditbusiness.hotel.entity.Reservation;
import org.zachary.creditbusiness.hotel.mapper.HotelMapper;
import org.zachary.creditbusiness.hotel.mapper.ReservationMapper;
import org.zachary.creditbusiness.hotel.service.HotelRecommendService;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class HotelRecommendServiceImpl
        extends ServiceImpl<HotelMapper, Hotel>
        implements HotelRecommendService {

    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private HotelMapper hotelMapper;

    @Override
    public List<Hotel> getHotelRecommendTops(Integer userId) {
        List<Hotel> result = new ArrayList<>();

        // 1. 加载该用户的所有订单，构建 <hotelId, count> 映射
        List<Reservation> userResList = reservationMapper.selectList(
                new QueryWrapper<Reservation>().eq("user_id", userId)
        );
        Map<Integer, Long> freqMap = userResList.stream()
                .collect(Collectors.groupingBy(Reservation::getHotelId, Collectors.counting()));

        // 2. 常住推荐：用户预订次数最多的酒店
        if (!freqMap.isEmpty()) {
            long maxFreq = Collections.max(freqMap.values());
            List<Integer> topHotelIds = freqMap.entrySet().stream()
                    .filter(e -> e.getValue() == maxFreq)
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());

            hotelMapper.selectBatchIds(topHotelIds).forEach(h -> {
                h.setNearby("常住推荐");
                h.setLocation(String.valueOf(freqMap.get(h.getId())));
                result.add(h);
            });
        }

        // 3. 人气推荐：评分最高的酒店，location 显示该用户的预订次数
        List<Hotel> allHotels = hotelMapper.selectList(new QueryWrapper<>());
        if (!allHotels.isEmpty()) {
            double maxScore = allHotels.stream()
                    .mapToDouble(Hotel::getScore)
                    .max()
                    .orElse(0);
            List<Hotel> topScoreHotels = allHotels.stream()
                    .filter(h -> h.getScore() == maxScore)
                    .toList();

            for (Hotel h : topScoreHotels) {
                long userCount = freqMap.getOrDefault(h.getId(), 0L);
                h.setNearby("人气推荐");
                h.setLocation(String.valueOf(userCount));
                result.add(h);
            }
        }

        return result;
    }
}